<template>
  <div class="">
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <e-heading>
        {{ (!id ? '新建' : '修改') + '招商计划'}}
        <small>
          <span>1.创建赛事</span>
          <span>2.创建招商计划</span>
          <span>3.通过平台审核</span>
          <span>4.平台招商</span>
          <span>5.签订协议</span>
          <span>6.招商成功</span>
        </small>
      </e-heading>
      <e-heading grade="2">基本信息</e-heading>
      <el-form
        ref="form"
        v-bind="getFormProps({labelWidth:'150px'})"
        :model="form"
        class="train-form">
        <el-form-item
          label="赛事选择："
          prop="sponsorBaseVO.matchId"
          :rules="rules.race">
          <el-col :span="20">
            <template>
              <el-select
                v-model="form.sponsorBaseVO.matchId"
                v-if="!id"
                placeholder="请选择赛事">
                <el-option
                  v-for="item in dict.match.data"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-input v-model="form.sponsorBaseVO.matchName" v-else disabled/>
            </template>

          </el-col>
        </el-form-item>

        <el-form-item label="招商方案："
          prop="sponsorBaseVO.sponsorName"
          :rules="rules.sponsorName">
          <el-col :span="20">
            <div class="remaining-box">
              <el-input
                :disabled="id?true:false"
                placeholder="请输入招商方案名称"
                v-model="form.sponsorBaseVO.sponsorName"
                :maxlength="40" number-word/>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="招商简介："
          prop="sponsorBaseVO.description"
          :rules="rules.description">
          <el-col :span="20">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3}"
              :maxlength="300"
              placeholder=" "
              v-model="form.sponsorBaseVO.description"
              number-word />
          </el-col>
        </el-form-item>
        <el-form-item label="招商数量："
          prop="sponsorBaseVO.quantity"
          :rules="rules.quantity">
          <el-col :span="20">
            <div class="remaining-box">
              <el-input
                class="w300"
                :maxlength="8"
                placeholder="请输入招商数量（数字）"
                v-model="form.sponsorBaseVO.quantity"/>
              <span class="unit">名</span>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="招商金额："
          prop="sponsorBaseVO.money"
          :rules="rules.money">
          <el-col :span="20">
            <div class="remaining-box">
              <el-input
                class="w300"
                :maxlength="8"
                placeholder="请输入招商金额（数字）"
                v-model="form.sponsorBaseVO.money"/>
              <span class="unit">万元起</span>
            </div>
          </el-col>
        </el-form-item>
        <e-heading grade="2">招商权益
          <small>请至少选择一个招商权益，招商权益填写的越详细，赞助商越有可能联系您。</small>
        </e-heading>
        <template>
          <div class="selectRule">{{rightsRule?'*至少选择一项招商权益':'' }}</div>
          <div v-for="(item,index) in form.rightsVOList" :key="item.parentRightsCode">
            <el-form-item
              :label="item.parentRightsName + '：'"
              prop="rights"
              :rules="index === 0?rules.contactRights:[]">
              <el-col :span="20">
                <el-select
                  class="input-block"
                  v-model="form.rightsVOList[index].rightsCodeArr"
                  @change="handlechangeselect(form.rightsVOList[index].rightsCodeArr,item,'rights')"
                  filterable
                  multiple>
                  <el-option
                    v-for="x in dict.dictBase.data[item.dictName]"
                    :key="x.value"
                    :label="x.label"
                    :value="x.value">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item
              label=""
              prop="rightsDesc"
              v-if="form.rightsVOList[index].rightsCodeArr.length>0">
              <el-col :span="20">
                <template>
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 3}"
                    :maxlength="1000"
                    placeholder=""
                    v-model="form.rightsVOList[index].rightsDesc" number-word />
                </template>
              </el-col>
            </el-form-item>
          </div>
        </template>

        <e-heading grade="2">传播渠道
          <small>请至少选择一个传播渠道</small>
        </e-heading>
        <template>
          <div class="selectRule">{{channelRule?'*至少选择一项传播渠道':'' }}</div>
          <el-form-item
            :label="item.channelTypeName + '：'"
            prop="channel"
            v-for="(item,index) in form.channelVOList"
            :key="item.channelType"
            :rules="index === 0?rules.contactChannel:[]">
            <el-col :span="20">
              <template v-if="item.channelType == 1">
                <el-select
                  class="input-block"
                  v-model="form.channelVOList[index].channelCodeArr"
                  @change="handlechangeselect(form.channelVOList[index].channelCodeArr,item,'channel')"
                  filterable
                  multiple>
                  <el-option-group
                  v-for="x in dict.dictBase.data[item.dictName]"
                  :key="x.label"
                  :label="x.label">
                  <el-option
                    v-for="y in x.data"
                    :key="y.value"
                    :label="y.label"
                    :value="y.value">
                  </el-option>
                </el-option-group>
                </el-select>
              </template>
              <template v-else>
                <el-select
                  class="input-block"
                  v-model="form.channelVOList[index].channelCodeArr"
                  @change="handlechangeselect(form.channelVOList[index].channelCodeArr,item,'channel')"
                  filterable
                  multiple>
                  <el-option
                    v-for="x in dict.dictBase.data[item.dictName]"
                    :key="x.value"
                    :label="x.label"
                    :value="x.value">
                  </el-option>
                </el-select>
              </template>
            </el-col>
          </el-form-item>
          <el-form-item label="补充内容（选填）：" prop="complement">
            <el-col :span="20">
              <el-input
                type="textarea"
                :autosize="{ minRows: 3}"
                :maxlength="200"
                placeholder=" "
                v-model="form.sponsorBaseVO.complement" number-word />
            </el-col>
          </el-form-item>
        </template>
        <e-heading grade="2">招商联系信息</e-heading>
        <template>
          <el-form-item label="联系人 ："
            prop="sponsorBaseVO.contactPerson"
            :rules="rules.contactPerson">
            <el-col :span="12">
              <el-input
                type="text"
                :maxlength="40"
                :minlength="2"
                placeholder="请输入联系人姓名"
                v-model="form.sponsorBaseVO.contactPerson" />
            </el-col>
          </el-form-item>
          <el-form-item label="联系电话 ："
            prop="sponsorBaseVO.contactPhone"
            :rules="rules.contactPhone">
            <el-col :span="12">
              <el-input
                type="text"
                :maxlength="11"
                placeholder="请输入联系电话"
                v-model="form.sponsorBaseVO.contactPhone" />
            </el-col>
          </el-form-item>
          <el-form-item
            label="联系邮箱（选填）："
            prop="sponsorBaseVO.contactEmail"
            :rules="rules.contactEmail">
            <el-col :span="12">
              <el-input
                type="text"
                :maxlength="40"
                placeholder="请输入联系邮箱"
                v-model="form.sponsorBaseVO.contactEmail" />
            </el-col>
          </el-form-item>
          <div class="el-form-item">
            <label class="el-form-item__label" style="width: 160px;">
                <span>附件（选填）</span>
                <el-tooltip class="item" effect="light" placement="top">
                  <div slot="content">支持格式： .xls;.xlsx;.txt;.jpg;.doc;.docx;.pdf;.ppt;.pptx;<br/>文件大小：10MB</div>
                  <i class="iconfont">&#xe690;</i>
                </el-tooltip>
                <span>：</span>
            </label>
            <div class="el-form-item__content" style="margin-left: 160px;">
              <div class="el-col el-col-12">
                <e-file-upload
                  :file-list.sync="form.fileVOList"
                  fileAccept=".xls,.xlsx,.txt,.jpg,.doc,.docx,.pdf,.ppt,.pptx"
                  :maxfileSize='10'>
                  <el-button>上传</el-button>
                </e-file-upload>
              </div>
            </div>
          </div>
          <!--<el-form-item label="附件（选填） ：">
            <el-col :span="12">
              <e-file-upload
                :file-list.sync="form.fileVOList"
                fileAccept=".xls,.xlsx,.txt,.jpg,.doc,.docx,.pdf,.ppt,.pptx">
                <el-row :gutter="20">
                  <el-col :span="6"><el-button>上传</el-button></el-col>
                  <el-col :span="18">
                    <span class="form-help">支持格式： .xls;.xlsx;.txt;.jpg;.doc; .docx;.pdf;.ppt;.pptx;
                                          <br>文件大小：10MB
                    </span>
                  </el-col>
                </el-row>
              </e-file-upload>
            </el-col>
          </el-form-item>-->
        </template>
        <div class="button-box">
          <el-button type="primary" native-type="submit" :loading="loading && loadingId == 1">确定提交</el-button>
          <!--<el-button v-if="!id" :loading="loading && loadingId == 0" @click="submit(0)">保存草稿</el-button>-->
          <el-button v-if="id" @click="submit(3)">放弃修改</el-button>
        </div>
      </el-form>
    </div>
  </div>

</template>

<script>
  import EFileUpload from '@e-ui/FileUpload'
  import validator from 'utils/validator'
  import { mapGetters } from 'vuex'
  import {form} from 'utils/mixins' // 引入form mixin
  import api from 'api/sponsor'
  export default {
    mixins: [form],
    components: {
      EFileUpload
    },
    computed: {
      ...mapGetters({
        dict: 'sponsor_dict'
      })
    },
    data () {
      let isCertify
      return {
        isCertify,
        id: this.$route.params.id,
        loading: false,
        rightsRule: true,
        channelRule: true,
        loadingId: '',
        form: {
          rightsVOList: [ // 招商权益
            {
              parentRightsCode: 1,
              parentRightsName: '知识产权权益',
              rightsCodeArr: [],
              rightsDesc: '',
              rightsName: '',
              dictName: 'ntellectualRights'
            },
            {
              parentRightsCode: 2,
              parentRightsName: '赛场广告权益',
              rightsCodeArr: [],
              rightsDesc: '',
              rightsName: '',
              dictName: 'raceAdRights'
            },
            {
              parentRightsCode: 3,
              parentRightsName: '媒体曝光权益',
              rightsCodeArr: [],
              rightsDesc: '',
              rightsName: '',
              dictName: 'mediaExpRights'
            },
            {
              parentRightsCode: 4,
              parentRightsName: '公共接待权益',
              rightsCodeArr: [],
              rightsDesc: '',
              rightsName: '',
              dictName: 'receptionRights'
            }
          ],
          channelVOList: [ // 传播渠道
            {
              channelType: 1,
              channelTypeName: '电视传播',
              channelCodeArr: [],
              channelValue: '',
              dictName: 'tvStation'
            },
            {
              channelType: 2,
              channelTypeName: '网络媒体',
              channelCodeArr: [],
              channelValue: '',
              dictName: 'networkMedia'
            },
            {
              channelType: 3,
              channelTypeName: '社交媒体',
              channelCodeArr: [],
              channelValue: '',
              dictName: 'socialMedia'
            },
            {
              channelType: 4,
              channelTypeName: '平面媒体',
              channelCodeArr: [],
              channelValue: '',
              dictName: 'planeMedia'
            },
            {
              channelType: 5,
              channelTypeName: '户外媒体',
              channelCodeArr: [],
              channelValue: '',
              dictName: 'outdoorMedia'
            }
          ],
          fileVOList: [],
          sponsorBaseVO: {
            auditStatus: '', // 审核状态 0 草稿 1 审核中 2 审核不通过 3 审核通过
            complement: '', // 招商渠道补充内容
            contactEmail: '', // 联系邮箱
            contactPerson: '', // 联系人
            contactPhone: '', // 联系电话
            description: '', // 招商简介
            id: '', // 招商Id
            matchId: '', // 关联赛事ID
            money: '', // 招商金额
            quantity: '', // 招商数量
            sponsorName: '', // 招商方案名称
            status: '0' // 招商状态（ 0 开启,1关闭 ）
          }
        },
        rules: {
          race: {required: true, message: '赛事不能为空'},
          sponsorName: {required: true, message: '招商方案不能为空'},
          description: [
            {required: true, message: '招商简介不能为空'},
            {min: 8, message: '招商简介至少为8个字'}
          ],
          quantity: [
            {required: true, message: '招商数量不能为空'},
            validator.rule.isIntadd
          ],
          money: [
            {required: true, message: '招商金额不能为空'},
            validator.rule.isIntadd
          ],
          contactPerson: [
            {required: true, message: '联系人不能为空'},
            {min: 2, max: 40, message: '请输入全名'}
          ],
          contactPhone: [
            {required: true, message: '联系电话不能为空'},
            validator.rule.phone
          ],
          contactEmail: [
            {required: true, message: '邮箱不能为空'},
            validator.rule.email
          ],
          contactChannel: [
            {
              validator: (rule, value, callback) => {
                let num = 0
                this.form.channelVOList.map(i => {
                  num += i.channelCodeArr.length
                })
                this.channelRule = num === 0
                return callback()
              }
            }
          ],
          contactRights: [
            {
              validator: (rule, value, callback) => {
                let num = 0
                this.form.rightsVOList.map(i => {
                  num += i.rightsCodeArr.length
                })
                this.rightsRule = num === 0
                return callback()
              }
            }
          ]
        }
      }
    },
    mounted () {
      if (this.id) { // 判断编辑 获取id的详细数据
        this.getdetailed(this.id)
      }
      this.$store.dispatch('sponsor_dict', 'match')
      this.$store.dispatch('sponsor_dict', 'dictBase')
    },
    methods: {
      getdetailed (id) { // 获取id数据
        api.business_detailed({sponsorId: id}).then((json) => {
          if (json.data.sponsorBaseVO.auditStatus === 1) this.$router.push({path: '/sponsor/business'})
          // console.log('开始数据', json.data)
          // 数据处理 普通表单合并
          this.form.sponsorBaseVO = json.data.sponsorBaseVO
          // 修改文件列表字段名
          for (let i in json.data.fileVOList) {
            this.form.fileVOList.push({
              name: json.data.fileVOList[i].fileName,
              path: json.data.fileVOList[i].fileUrl
            })
          }
          // 数组合并方法
          let mergeData = (odata, ndata, key) => {
            if (typeof ndata === 'object') {
              ndata.map(i => {
                odata.map(j => {
                  if (i[key] === j[key]) {
                    for (let k in i) {
                      j[k] = i[k]
                    }
                  }
                })
              })
            }
          }
          mergeData(this.form.channelVOList, json.data.channelVOList, 'channelType')
          mergeData(this.form.rightsVOList, json.data.rightsVOList, 'parentRightsCode')
        }, () => {
          this.$router.push({path: '/sponsor/business'})
        })
      },
      submit (type = 1) {
        // 提交   type  1提交 0草稿 3放弃
        this.loadingId = type
        if (type === 3) {
          this.$router.push({path: '/sponsor/business'})
          return
        }
        if (!this.rightsRule && !this.channelRule) {
          this.removeKey()
          this.form.sponsorBaseVO.auditStatus = type // 设置保存、草稿状态
          if (this.form.sponsorBaseVO.id) {
            api.business_edit(JSON.stringify(this.form), {context: this, successMsg: 'none'}).then((json) => {
              this.handleSubmitSuccess(type, this.form.sponsorBaseVO.id)
            })
          } else {
            api.business_add(JSON.stringify(this.form), {context: this, successMsg: 'none'}).then((json) => {
              this.handleSubmitSuccess(type, this.form.sponsorBaseVO.id)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      },
      removeKey () { // 删除一些文件上传组件产生的多余的KEY、接口返回多余key
        this.form.fileVOList.map(i => {
          return {
            name: i.name,
            path: i.path
          }
        })
        this.form.channelVOList.map(i => {
          delete i.updateTime
          delete i.createTime
        })
        this.form.rightsVOList.map(i => {
          delete i.createTime
          delete i.updateTime
        })
      },
      handleSubmitSuccess (type, id) { // 成功弹窗
        let that = this
        let text = [
          {
            title: (id ? '修改' : '新建') + '招商计划草稿成功!',
            text: '草稿保存到招商计划列表中！'
          },
          {
            title: (id ? '修改' : '新建') + '招商计划成功!',
            text: '我们会在3个工作之内完成审核，请耐心等待！'
          }
        ]
        this.$confirm(text[type].text, text[type].title, {
          type: 'success',
          showCancelButton: false,
          callback () {
            that.$router.push({path: '/sponsor/business'})
          }
        })
      },
      handlechangeselect (value, item, type) { // 多选选中后，输出详细value字符串
        type === 'rights' ? this.$refs.form.validateField('rights') : this.$refs.form.validateField('channel')
        let dict = this.dict.dictBase.data[item.dictName]
        let label = ''
        value.map((i) => {
          dict.map((j) => {
            if (j.data) {
              j.data.map((k) => {
                if (i === k.value) label += k.label + ';'
              })
            } else {
              if (i === j.value) label += j.label + ';'
            }
          })
        })
        if (item.rightsName || item.rightsName === '') {
          item.rightsName = label
        } else if (item.channelValue || item.channelValue === '') {
          item.channelValue = label
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  
  .heading small span{
    margin: 0 10px;
  }
  .unit{
    margin-left: 10px;
  }
  .w300{
    width: 300px;
  }
  input[type="number"]::-webkit-outer-spin-button,
  input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"]{
    -moz-appearance: textfield;
  }
  .selectRule{
    height: 30px;
    color: $color-error;
    padding-left: 160px;
  }
</style>
